package com.ruoyi.common.utils;
import com.ruoyi.common.core.domain.hospital.MrOutData;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.transform.*;
import javax.xml.transform.stream.StreamResult;
import java.io.StringReader;
import java.io.StringWriter;

public class MrOutDataUtils {

    public static MrOutData getMrOutData(String data) throws JAXBException {
        MrOutData mrOutDataList = new MrOutData();
        try {

            JAXBContext jaxbContext = JAXBContext.newInstance(MrOutData.class);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            StringReader reader = new StringReader(data);
            mrOutDataList = (MrOutData) jaxbUnmarshaller.unmarshal(reader);

        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return mrOutDataList;
    }

    public static String MrOutDataToXML(MrOutData person) throws JAXBException, TransformerException {
        JAXBContext jaxbContext = JAXBContext.newInstance(MrOutData.class);

        Marshaller jaxbMarshaller = jaxbContext.createMarshaller();

        // 输出格式化
        jaxbMarshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

        StringWriter sw = new StringWriter();
        jaxbMarshaller.marshal(person, sw);

        // 获取生成的XML字符串（包含XML声明头）
        String xmlWithDeclaration = sw.toString();

        // 使用Transformer来移除XML声明头
        TransformerFactory transformerFactory = TransformerFactory.newInstance();
        Transformer transformer = transformerFactory.newTransformer();
        transformer.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");

        // 由于StringSource不是标准API的一部分，我们使用StreamSource并跳过XML声明
        // 我们通过Transformer直接输出到另一个StringWriter来避免XML声明
        Source inputSource = new javax.xml.transform.stream.StreamSource(new java.io.StringReader(xmlWithDeclaration));
        StringWriter outputStringWriter = new StringWriter();
        StreamResult outputStreamResult = new StreamResult(outputStringWriter);

        // 执行转换
        transformer.transform(inputSource, outputStreamResult);

        // 获取最终的XML字符串（不带XML声明头）
        String xmlWithoutDeclaration = outputStringWriter.toString();

        return xmlWithoutDeclaration;
    }

}
